<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/8/19
 * Time: 11:56 AM
 */
namespace app\wechat\logic;

use EasyWeChat\Factory;
use think\Db;

class App
{
    public static $weChatInfo;
    
    function __construct($idOrAppId)
    {
        $weChatInfo = Db::table('wechat')
            ->field('id,name,appid,appsecret,token,encode_asc_key,wechat_id')
            ->where('id|appid',$idOrAppId)
            ->where('status',1)
            ->cache(5)
            ->find();
        
        if(empty($weChatInfo)){
            throw new \Exception('查询公众号消息失败');   
        }
        self::$weChatInfo = $weChatInfo;
    }

    public function getApp($config = [])
    {
        $config = array_filter(array_merge([
            'app_id'  => self::$weChatInfo['appid'],
            'secret'  => self::$weChatInfo['appsecret'],
            'token'   => self::$weChatInfo['token'],
            'aes_key' => self::$weChatInfo['encode_asc_key'],
            'response_type' => 'array',
        ],$config));
        
        return Factory::officialAccount($config);
    }
    
    public function getAccessToken()
    {
        $wApp = $this->getApp();
        $accessToken = $wApp->access_token;
        $token = $accessToken->getToken();
        return $token;
    }
    
    public function getWeChatInfo()
    {
        return self::$weChatInfo;
    }
}